//面向对象工厂,封装插件
(function(root, factory, plug) {
	factory(root.jQuery, plug);
})(window, function($, plug) {
	//播放器对象
	var Model = {
		//全局变量
		data: function() {
			file = $(this).find('video').get(0),
			fileNum = 0, /*文件类型*/
			fileIndex = 0, /*歌曲顺序*/
			modeNum = 0, /*播放模式*/
			widScreen = false, /*全屏控制*/
			webScreen = false, /*全屏控制*/
			fullScreen = false, /*全屏控制*/
			inputing = false; /*正在输入*/
			theme = themeList[0],
			speed = 1,
			speedList = [0.5,0.75,1,1.25,1.5,2],
			hdList = [
				"高清 1080P",
				"高清 720P",
				"清晰 480P",
				"流畅 360P",
				"自动"
			],
			hdType = [
				"1080P","720P","480P","360P","自动"
			],
			dmColorList=[
				"#FE0302",
				"#FF7204",
				"#FFAA02",
				"#FFD302",
				"#FFFF00",
				"#A0EE00",
				"#00CD00",
				"#019899",
				"#4266BE",
				"#89D5FF",
				"#CC0273",
				"#222222",
				"#9B9B9B",
				"#FFFFFF"
			],
			dmColor="",
			dmSizeList=[14,18],
			dmSize="",
			dmModeList=[1,2,3],
			dmMode="",
			dmList = []
		},
		//构建播放器
		components: function() {
			//创建歌单
			function addList(obj, arr) {
				for (var i = 0; i < arr.length; i++) {
					obj.innerHTML += 
					"<li>"+
						"<p>" +(i + 1) + "</p>"+
						"<p title=" +arr[i].name + ">" +arr[i].name + "</p>"+
						"<p>" +arr[i].dur + "</p>"+
					"</li>"
				}
			}
			
			//选集
			function getList(obj, arr) {
				for (var i = 0; i < arr.length; i++) {
					obj.innerHTML += 
					"<li>"+
						"<p>" +(i + 1) + "</p>"+
						"<p title=" +arr[i].name + ">" +arr[i].name + "</p>"
					"</li>"
				}
			}
			
			$('.video-flies').addTag('div', fileList.length).each(function(i) {
				$(this).html(
					fileList[i].classify + '(<b class="player-Len"></b>)'
				);
			})
			
			for (var i = 0; i < fileList.length; i++) {
				$('.player-Len').eq(i).html(fileList[i].list.length);
			}
			
			$('.video-list').addTag('ul', fileList.length);
			$('.video-list ul').each(function(i) {
				addList(this, fileList[i].list);
			});
			
			$('.video-list ul li').eq(0).css("color",theme);
			
			$('.play-speed dl').addTag('dd', speedList.length).each(function(i){
				$(this).html(speedList[i]);
			});
			
			$('.sel-list').addTag('ul', fileList.length);
			$('.sel-list ul').each(function(i) {
				getList(this, fileList[i].list);
				if(fileList[i].list.length>=5){
					$('.sel-list').css({
						"height":"120px"
					});
				}else{
					$('.sel-list').css({
						"height":"auto"
					});
				}
			})
		},
		//控制播放器
		methods: function() {
			//默认设置
			file.src = path + fileList[fileNum].folder + '/' + 
			fileList[fileNum].list[fileIndex].name + '.mp4' 
			//+ fileList[fileNum].type;
			file.volume = 0.5;
			dmColor = dmColorList[13];
			dmSize = dmSizeList[0];
			dmMode = dmModeList[0];
			$('.vol-num').html(parseInt(file.volume*100));
			$('.bili-player-top').html(fileList[fileNum].list[fileIndex].name);
			
			//视频监控
			file.addEventListener("timeupdate", function() {
				var dur = file.duration,
					cur = file.currentTime,
					scale = cur / dur;
					file.playbackRate = speed;
				$('.pro-line').width(scale * $('.progress').width());
				$('.pro-bar').css('left',scale * $('.progress').width());
				if(cur==0){
					$('.duration').html("00:00 / 00:00");
				}else{
					$('.duration').html(formatTime(cur)+" / "+formatTime(dur));
				}
				if (cur == dur) {
					_playTpye();
				}
				auto_dm(formatTime(cur));
			});
			
			//控制台按钮
			$(".play").click(function(){
				_play();	
			})
			$(".prev").click(function(){
				_prev();	
			})
			$(".next").click(function(){
				_next();	
			})
			$(".wid-screen").click(function(){
				_widScreen();	
			})
			
			$(".web-screen").click(function(){
				_webScreen();	
			})
			$(".full-screen").click(function(){
				_fullScreen();	
			})
			
			//全屏隐藏控制台
			$(".bili-player-wrap").hover(function(){
				$(".bili-player-control").css("display","block")
			},function(){
				if(widScreen==true){
					$(".bili-player-control").css("display","none");
					/* setTimeout(function(){
						
					},3000) */
				}else{
					$(".bili-player-control").css("display","block");
				}
			})
			
			//点击播放
			$(".bili-player-video").click(function(){
				_play();
			});
			$(".bili-player-video").hover(function(){
				$(".vol-set").css("display","none");
				$(".setting").css("display","none");
				$(".hd-list").css("display","none");
			})
			
			//进度条
			$('.progress').hover(function() {
				$('.pro-time').css('display', 'block');
				$(document).mousemove(function(ev) {
					var $p = $('.progress'),
						disX = ev.clientX - $p.offset().left,
						scale = disX / $p.width();
					$('.pro-time').html(formatTime(scale * file.duration));
					if(disX<30){
						$('.pro-time').css('left', disX)
					}else if(disX > $p.width()-60){
						$('.pro-time').css('left', disX-60)
					}else{
						$('.pro-time').css('left', disX-30)
					}
				})
			}, function() {
				$('.pro-time').css('display', 'none');
			});
			
			//点击进度条
			$('.progress').click(function(e) {
				var $p = $('.progress');
				var oEvent = e || event,
				disX = oEvent.clientX - $p.offset().left,
				scale = disX / $p.width();		
				$('.pro-line').width(disX);
				$('.pro-bar').css("left",disX);	
				var dur = file.duration,
				cur = file.currentTime = dur * scale;
				$('.duration').html(formatTime(cur) + ' / '
				 + formatTime(dur));
			});
			
			//调节进度条
			$(".pro-bar").drag(function(l,t){
				$(".pro-bar").css("left",l);
				$(".pro-line").width(l);
				var scale = l / $('.progress').width();
				var dur = file.duration,
					cur = file.currentTime = dur * scale;
				$('.duration').html(formatTime(cur)+" / "+formatTime(dur));
			})

			// 调节音量
			$('.vol-bar').drag(function(l, t) {
				var h = $('.vol-bg').height();
					H = h - $('.vol-bar').height();
				var scale = 1 - (t / H) ;
				file.volume = scale;
				$('.vol-bar').css({"top": t});
				console.log(t)
				if (scale == 0) {
					$('.vol-get').html('&#xe645');
				} else {
					$('.vol-get').html('&#xe605');
				}
				$('.vol-num').html(parseInt(scale*100));
				$('.vol-line').height(scale * h );
			});
			
			//点击音量
			$('.vol-bg').click(function(e) {
				var oEvent = e || event;
				var disY = oEvent.clientY - $('.vol-bg').get(0).offsetTop,
					scale = disY / this.offsetHeight;
					console.log(oEvent.clientY-$('.vol').get(0).offsetTop+100)
				/* $('.vol-line').height(disY);
				$('.vol-get').html('&#xe605;');
				file.volume = scale; */
			});
			
			//静音
			$('.vol-get').click(function(){
				_voice();
			})
			
			$('.vol').hover(function(){
				$(".vol-set").css("display","block")
			}).siblings().hover(function(){
				$(".vol-set").css("display","none")
			})
			
			$(".selector").hover(function(){
				$(".sel-list").show();
			}).siblings().hover(function(){
				$(".sel-list").hide();
			})
			
			//点歌
			$('.video-flies div').each(function(i) {
				$(this).click(function() {
					fileNum = $(this).index();
					$(this).css({
						'background': theme,
						'color':'#fff'
					}).siblings().css({
						'background': '#fff',
						'color':'#666'
					});
					$('.video-list ul').eq(fileNum).show().siblings().hide();
					$('.sel-list ul').eq(fileNum).show().siblings().hide();
				})
				
				$('.video-list ul').eq(i).find('li').click(function() {
					fileIndex = $(this).index();
					$(this).css({'color':theme}).siblings()
					.css({'color':'#666'})
					$('.video-list ul').eq(i).siblings()
					.find('li').css({'color':'#666'});
					$(".bili-player-top").html(fileList[fileNum].list[fileIndex].name)
					_replay();
				})
				
				$('.sel-list ul').eq(i).find('li').click(function() {
					fileIndex = $(this).index();
					$(this).css({'color':'#2399ea'}).siblings()
					.css({'color':'#fff'})
					_replay();
				})
			})
			
			
			//设置
			$('.set').hover(function(){
				$(".setting").css("display","block")
			}).siblings().hover(function(){
				$(".setting").css("display","none")
			})
			
			//模式选择
			$('.play-way ul li').each(function(i) {
				$(this).click(function() {
					modeNum = i;
					$(this).css("background","#2399ea")
					.siblings().css("background","gray");
				})
			});
			
			//播放速率
			$('.play-speed dl dd').each(function(i) {
				$(this).click(function() {
					$(this).css("color","#2399ea").siblings().css("color","#fff");
					var _index = $(this).index();
					speed = speedList[_index]
					$(".quick-play input").get(0).checked = false;
				})
			});
			
			//清晰度
			$(".hd").hover(function(){
				$(".hd-list").css("display","block")
			}).siblings().hover(function(){
				$(".hd-list").css("display","none")
			})
			
			$('.hd-list ul').addTag('li',hdList.length).each(function(i){
				$(this).html(hdList[i])
				$(this).click(function(){
					$(".hd-show").html(hdType[i])
					$('.hd-list ul li').eq(i)
					.css("color","#2399ea").siblings()
					.css("color","#fff");
					$(".hd-list").css("display","none")
				})
			});
			$(".hd-list ul li").hover(function(){
				$(this).css("background","rgba(125,125,125,0.5)")
				.siblings().css("background","#000");
			})
			
			//快速播放
			$(".quick-play input").click(function(){
				quickPlay(this);
			})
			
			$(".dm-set-font-color ul").addTag('li',dmColorList.length).each(function(i){
				$(this).css("background",dmColorList[i]);
				$(this).click(function(){
					$(this).addClass("dm-text-color").siblings().removeClass("dm-text-color");
					dmColor = dmColorList[i];
					$(".show-dm-box").css("background",dmColor)
					$(".dm-set-font-color input").val(dmColor);
				})
			})
			
			$(".dm-set-font-size p").each(function(i){
				$(this).click(function(){
					dmSize = dmSizeList[i];
					console.log(dmSize);
					$(this).addClass("dm-selin-font").siblings().removeClass("dm-selin-font");
				})
			})
			
			$(".dm-set-mode p").each(function(i){
				$(this).click(function(){
					dmMode = dmModeList[i];
					$(this).addClass("dm-selin-hei").siblings().removeClass("dm-selin-hei");
				})
			})
			
			//发弹幕
			$(".danmu-content").focus(function(){
				inputing=true;
			});
			
			$(".danmu-content").blur(function(){
				inputing=false;
			});
			
			$('.danmu-btn').click(function(){
				send_dm();
				inputing=false;
			})
			
			//方法库
			
			//播放
			function _play() {
				if (file.paused) {
					$('.play').html('&#xe721;');
					$('.bili-player-state').html('');
					file.play();
				} else {
					$('.play').html('&#xe686;');
					$('.bili-player-state').html('&#xe6bc;');
					file.pause();
				}
			}
			
			//播放类型
			function _playTpye() {
				var dur = file.duration;
				var cur = file.currentTime;
				switch (modeNum) {
					/*单曲*/
					case 0:
						if (cur == dur) {
							file.currentTime = 0;
						}
						_replay();
					break;
					/*列表*/
					case 1:
						fileIndex++;
						if (fileIndex > fileList[fileNum].list.length - 1) {
							fileIndex = 0;
						}
						_replay();
					break;
					/*随机*/
					case 2:
						if (cur == dur) {
							file.currentTime = 0;
							file.pause();
							$('.play').html('&#xe686;');
							$('.bili-player-state').html('&#xe6bc;');
						}
						/* fileIndex = parseInt(Math.random() * 
						fileList[fileNum].list.length); */
					break;
				}
				
			}
			
			//循环播放
			function _replay() {
				file.src = path + fileList[fileNum].folder + '/' +
				fileList[fileNum].list[fileIndex].name + '.mp4' 
				//+fileList[fileNum].type;
				_play();
				//改变样式
				$('.video-list ul li p').removeClass('hover');
				$('.video-list ul li p').eq(fileIndex).addClass('hover');
				$('.play').html('&#xe721;');
				$('.video-list ul').eq(fileNum).find('li').eq(fileIndex)
				.css({'color':theme}).siblings().css({'color':'#666'})
				$('.video-list ul').eq(fileNum).siblings().find('li')
				.css({'color':'#666'});
				$('.play-speed dl dd').eq(2).css({
					'color':'#2399ea','font-weight':'700'})
					.siblings().css({'color':'#fff','font-weight':'400'});
				$(".sel-list ul").eq(fileNum).find('li').eq(fileIndex)
				.css({'color':'#2399ea'}).siblings().css({'color':'#fff'})
			}
			
			//快进
			function _fast() {
				var cur = file.currentTime;
				var dur = file.duration;
				cur += 10;
				file.currentTime = cur;
				if (cur > dur) {
					cur = dur;
				}
				var scale = cur / dur;
				$('.pro-line').width(scale * $('.pro-bg').width());
			}
			
			//回退
			function _back() {
				var cur = file.currentTime;
				var dur = file.duration;
				cur -= 10;
				file.currentTime = cur;
				if (cur < 0) {
					cur = 0;
				}
				var scale = cur / dur;
				$('.pro-line').width(scale * $('.pro-bg').width());
			}
			
			//下一首
			function _next() {
				if (fileIndex < fileList[fileNum].list.length - 1) {
					fileIndex++;
				} else {
					fileIndex = 0;
				}
				_replay();
			}
			
			//上一首
			function _prev() {
				if (fileIndex > 0) {
					fileIndex--;
				} else {
					fileIndex = fileList[fileNum].list.length - 1;
				}
				_replay();
			}
			
			//增加音量
			function _up() {
				var vol = file.volume;
				vol += 0.1;
				$('.vol-num').html(parseInt(vol*100));
				$('.vol-line').height(parseInt(vol*62)); 
				$('.vol-bar').css('top', 50-parseInt(vol*50));
				if (vol > 1) {
					vol = 1;
					$('.vol-num').html(100);
					$('.vol-line').height(62); 
					$('.vol-bar').css('top',0);
				}
				file.volume = vol;
			}
			
			//切换列表
			function _toggleUp(){
				if(fileNum < fileList.length-1){
					fileNum ++;
				}else{
					fileNum = 0;
				}
				changeList();
			}
			
			function _toggleDown(){
				if(fileNum >= 0){
					fileNum --;
				}else{
					fileNum = fileList.length-1;
				}
				changeList();
			}
			
			//改变列表
			function changeList(){
				fileIndex = 0;
				$('.video-flies div').eq(fileNum).css({
					'background': theme,
					'color':'#fff'
				}).siblings().css({
					'background': '#fff',
					'color':'#666'
				});
				$('.video-list ul').eq(fileNum).show().siblings().hide();
				$('.sel-list ul').eq(fileNum).show().siblings().hide();
			}
			
			//降低音量
			function _down() {
				var vol = file.volume;
				vol -= 0.1;
				$('.vol-num').html(parseInt(vol*100));
				$('.vol-line').height(parseInt(vol*62)); 
				$('.vol-bar').css('top', 50-parseInt(vol*50));
				if (vol < 0) {
					vol = 0;
					$('.vol-num').html(0);
					$('.vol-bar').css('top',50);
					$('.vol-line').height(0); 
				}
				file.volume = vol;
			}
			
			//静音, 随机音量
			function _voice(){
				var H = $('.vol-bg').height() - $('.vol-bar').height();
				if (file.volume != 0) {
					file.volume = 0;
					$('.vol-num').html(0);
					$('.vol-get').html('&#xe6b2');
					$('.vol-line').height(0);
					$('.vol-bar').css("top",H);
				} else {
					var scale = Math.random();
					file.volume = scale;
					$('.vol-num').html(parseInt(scale*100));
					$('.vol-get').html('&#xe602');
					$('.vol-line').height(scale * H);
					$('.vol-bar').css('top', H - scale * H);
				}
			}
			
			//快速浏览
			function quickPlay(checkbox){
				if (checkbox.checked == true){
					speed = 12;
					modeNum = 1;
				}else{
					speed=1;
					modeNum = 0;
				}
			}
			
			//退出全屏
			function _backScreen(){
				$(".bili-video-list").css("display","block");
				$(".bili-player-top").css("display","block");
				$(".selector").css("display","none");
				$(".bili-player").css({
					"width":988,"height":448,"margin":"10px auto"
				});
				$(".bili-player-wrap").css({
					"width":638,"height":448
				});
				$(".bili-player-video").css({
					"width":624,"height":350
				});
				$(".bili-player-control").css("bottom","0");
				widScreen = false;
			}
			
			//宽屏
			function _widScreen(){
				if(widScreen==false){
					$(".bili-video-list").css("display","none");
					$(".bili-player-top").css("display","none");
					$(".selector").css("display","block");
					$(".bili-player").css({
						"width":988,"height":556,"margin":"10px auto"
					});
					$(".bili-player-wrap").css({
						"width":988,"height":556
					});
					$(".bili-player-video").css({
						"width":988,"height":556
					});
					$(".bili-player-control").css("bottom","0");
					widScreen = true;
				}else{
					_backScreen()
					webScreen = false
				}
			}
			
			//网页全屏
			function _webScreen(){
				if(webScreen==false){
					$(".bili-video-list").css("display","none");
					$(".bili-player-top").css("display","none");
					$(".selector").css("display","block");
					var w = $(document).width();
					var h = $(document).height();
					$(".bili-player").css({
						"width":w,"height":h,"margin":0
					});
					$(".bili-player-wrap").css({
						"width":w,"height":h
					});
					$(".bili-player-video").css({
						"width":w,"height":h
					});
					$(".bili-player-control").css("bottom","0");
					webScreen = true;
				}else{
					_backScreen();
					webScreen = false;
				}
			}
			
			// 全屏兼容代码
			function requestFullscreen(ele) {
			    if (ele.requestFullscreen) {
			        ele.requestFullscreen();
			    } else if (ele.webkitRequestFullscreen) {
			        ele.webkitRequestFullscreen();
			    } else if (ele.mozRequestFullScreen) {
			        ele.mozRequestFullScreen();
			    } else if (ele.msRequestFullscreen) {
			        ele.msRequestFullscreen();
			    }
			}
			
			//全屏播放
			function _fullScreen(){
				//requestFullscreen(file);
				if(fullScreen==false){
					requestFullscreen(file);
					fullScreen = true;
				}else{
					_backScreen();
					fullScreen = false;
				}
			}
			
			
			//发送弹幕
			function send_dm(){
				var dm="";
				var dmInput = $('.danmu-content')[0];
				if(dmInput.value){
					dm = dmInput.value;
					dmText(dm,dmColor,dmSize);
					dmInput.value="";
				}
			}
			
			//自动发弹幕
			function auto_dm(cur){
				sending = true;
				dmList = fileList[fileNum].list[fileIndex].dmList;
				if(dmList.length!=0){
					for(var i=0;i<dmList.length;i++){
						if(cur==dmList[i].time){
							dmText(dmList[i].content,dmList[i].color,dmList[i].size)
						}
					}
				}
			}
			
			//设置弹幕文字
			function dmText(text,color,size){
				var dmBox = $('.bili-player-video')[0];
				var dmCon=document.createElement('div');
				dmCon.innerHTML=text;
				var W = dmBox.offsetWidth;
				var H = dmBox.offsetHeight;
				dmCon.className="danmu-text";
				dmCon.style.color = color;
				dmCon.style.fontSize = size + "px";
				dmBox.appendChild(dmCon);
				var w = dmCon.offsetWidth;
				switch (dmMode){
					case 1:
						var t = Math.ceil(Math.random()*H*0.8);
						dmCon.style.left=(W-w)+"px";
						dmCon.style.top = t + 'px';
						dmMove(dmCon,'left',-w,-W/300,function(){
							var l = -1*dmCon.offsetLeft;
							if(l >= w){
								dmBox.removeChild(dmCon)
								clearInterval(dmCon.timer);
							}
						});
						
					break;
					case 2:
						dmCon.style.left = (W-w)*0.5+'px';
						dmCon.style.top = H*0.1+'px';
						window.setTimeout(function() {
							dmBox.removeChild(dmCon)						
						},3000)
					break;
					case 3:
						dmCon.style.left = (W-w)*0.5+'px';
						dmCon.style.top = H*0.9+'px';
						window.setTimeout(function() {
							dmBox.removeChild(dmCon)						
						},3000)
					break;
				}
				
			}
			
			//随机颜色
			function getColor(obj){
				var r=Math.ceil(Math.random()*255);
				var g=Math.ceil(Math.random()*255);
				var b=Math.ceil(Math.random()*255);
				obj.style.color="rgb("+r+","+g+","+b+")";
			}
			
			//获取样式
			function getStyle(obj,name){
				if(obj.currentStyle){
					return obj.currentStyle[name];
				}
				else{
					return getComputedStyle(obj,false)[name];
				}
			}
			
			//弹幕移动
			function dmMove(obj,attr,iTarget,speed,callback){
				clearInterval(obj.timer);
				obj.timer=setInterval(function(){
					var cur=0;
					if(attr=='opacity'){
						cur=parseFloat(getStyle(obj,attr))*100;
					}
					else{
						cur=parseInt(getStyle(obj,attr));
					}
					if(cur==iTarget){
						clearInterval(obj.timer);
					}
					else{
						if(attr=='opacity'){
							obj.style.filter='alpha(opacity:'+(cur+speed)+')';
							obj.style.opacity=(cur+speed)/100;
						}
						else{
							obj.style[attr]=cur+speed+'px';
						}
					}
					callback();
				},30);
			}
			
			
			//转成时间格式
			function formatTime(time) {
				var m = 0,
					s = parseInt(time);
				if (s > 60) {
					m = parseInt(s / 60);
					s = parseInt(s % 60);
				}
				var zero = function(v) {
					return (v >> 0) < 10 ? "0" + v : v;
				};
				return zero(m) + ":" + zero(s);
			};
			
			//键盘操作
			$(window).keydown(function(event) {
				switch (event.keyCode) {
					case 188:	//全屏播放 : 0键
						_widScreen();
					break;
					case 190:	//全屏播放 : 0键
						_webScreen();
					break;
					case 190:	//控制台升起 : 点键
						//_conUp();
					break;
					case 32:	//播放 : 空格键
						if(inputing==false){
							_play();
						}
					break;
					case 37:	//回退 : 左键
						_back();
					break;
					case 38:	//上一首 : 上键
						_prev();
					break;
					case 39:	//快进 : 右键
						_fast();
					break;
					case 40:	//下一首 : 下键
						_next();
					break;
					case 27:	//退出全屏 : Esc
						_backScreen();
					break;
					case 219:	//增加音量 :[
						_down();
					break;
					case 221:	//减少音量 : ]
						_up();
					break;
					case 222:	//减少音量 : ]
						_toggleUp();
					break;
					case 186:	//减少音量 : ]
						_toggleDown();
					break;
					case 13:	//减少音量 : ]
						/* _replay(); */
						send_dm();
						//inputing=false;
					break;
				}
			})
		},
	};
	
	//启用
	$.fn[plug] = function(options) {	
		$.extend(this,Model,options);
		this.data();
		this.components();
		this.methods();
		return this;
	}
}, "player");